import React from "react";
import { Link, Routes, Route, Navigate } from "react-router-dom";

const Login = () => {
  return <div>这是登录页面</div>;
};

const Home = () => {
  return <div>这是首页</div>;
};
const About = () => {
  return <div>这是关于页</div>;
};
const Mine = () => {
  // const navigate = useNavigate();

  // useEffect(() => {
  //   // 判断是否登陆过
  //   if (!localStorage.getItem("token")) {
  //     navigate("/login");
  //   }
  // }, [navigate]);
  return <div>这是我的页</div>;
};

const Auth = (props) => {
  if (localStorage.getItem("token")) {
    return props.children;
  } else {
    return <Navigate to="/login" replace></Navigate>;
  }
};

const App = () => {
  return (
    <>
      <h2>路由鉴权</h2>
      <ul>
        <li>
          <Link to="/home">首页</Link>
        </li>
        <li>
          <Link to="/about">关于页</Link>
        </li>
        <li>
          <Link to="/mine">我的页</Link>
        </li>
      </ul>

      <hr />

      <Routes>
        <Route path="/home" element={<Home />}></Route>
        <Route
          path="/about"
          element={
            <Auth>
              <About />
            </Auth>
          }
        ></Route>
        <Route
          path="/mine"
          element={
            <Auth>
              <Mine />
            </Auth>
          }
        ></Route>
        <Route path="/login" element={<Login />}></Route>
      </Routes>
    </>
  );
};

export default App;
